package com.retail.shop.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.retail.core.common.AbstractCommonController;
import com.retail.core.entity.ParamReq;

import com.retail.core.entity.result.PageResult;
import com.retail.core.entity.result.Result;
import com.retail.global.security.LoginUser;
import com.retail.global.security.LoginUserUtil;
import com.retail.global.annon.TraceLog;
import com.retail.shop.client.RetailShopClient;
import com.retail.shop.entity.request.RetailShopRequest;
import com.retail.shop.entity.vo.RetailShopVo;
import com.retail.shop.service.RetailShopService;
import com.retail.system.entity.vo.TableTreeVo;
import com.retail.system.enums.UserTypeEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 商户信息 API
 *
 * @author Administrator
 */
@Api(tags = "商户信息 API")
@RestController
@RequestMapping("/retailShop")
public class RetailShopController extends AbstractCommonController<RetailShopService, RetailShopRequest, RetailShopVo> {

    private final RetailShopService retailShopService;

    @Autowired
    private RetailShopClient retailShopClient;

    public RetailShopController(RetailShopService retailShopService) {
        this.retailShopService = retailShopService;
    }

    @TraceLog()
    @GetMapping("{id}")
    public Result getModel(@PathVariable("id") Long id) {
        return super.getModel(retailShopService, id);
    }

    @TraceLog()
    @PostMapping
    @ApiOperation("保存商户信息")
    public Result<Integer> save(@RequestBody RetailShopRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());

        if (ObjectUtil.isNotEmpty(request.getSanitaryLicensePhotos())) {
            request.setSanitaryLicensePhoto(request.getSanitaryLicensePhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setSanitaryLicensePhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getBusinessLicensePhotos())) {
            request.setBusinessLicense(request.getBusinessLicensePhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setBusinessLicense("");
        }

        if (ObjectUtil.isNotEmpty(request.getCorporationPhotos())) {
            request.setCorporationPhoto(request.getCorporationPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setCorporationPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getDoorPhotos())) {
            request.setDoorPhoto(request.getDoorPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setDoorPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getEvnPhotos())) {
            request.setEvnPhoto(request.getEvnPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setEvnPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getDouyinPhotos())) {
            request.setDouyinPhoto(request.getDouyinPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setDouyinPhoto("");
        }
        return super.save(retailShopService, request);
    }

    @TraceLog()
    @PostMapping("insertOrUpdateRetailShop")
    @ApiOperation("保存或者修改信息")
    public Result<Integer> insertOrUpdateRetailShop(@RequestBody RetailShopRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());

        if (ObjectUtil.isNotEmpty(request.getSanitaryLicensePhotos())) {
            request.setSanitaryLicensePhoto(request.getSanitaryLicensePhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setSanitaryLicensePhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getBusinessLicensePhotos())) {
            request.setBusinessLicense(request.getBusinessLicensePhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setBusinessLicense("");
        }

        if (ObjectUtil.isNotEmpty(request.getCorporationPhotos())) {
            request.setCorporationPhoto(request.getCorporationPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setCorporationPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getDoorPhotos())) {
            request.setDoorPhoto(request.getDoorPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setDoorPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getEvnPhotos())) {
            request.setEvnPhoto(request.getEvnPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setEvnPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getDouyinPhotos())) {
            request.setDouyinPhoto(request.getDouyinPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setDouyinPhoto("");
        }

        return retailShopService.insertOrUpdateRetailShop(request);
    }

    @TraceLog()
    @PutMapping
    @ApiOperation("更新商户信息")
    public Result<Integer> update(@RequestBody RetailShopRequest request) {
        request.setCreateUser(LoginUserUtil.getUserId());
        if (ObjectUtil.isNotEmpty(request.getSanitaryLicensePhotos())) {
            request.setSanitaryLicensePhoto(request.getSanitaryLicensePhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setSanitaryLicensePhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getBusinessLicensePhotos())) {
            request.setBusinessLicensePhoto(request.getBusinessLicensePhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setBusinessLicensePhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getCorporationPhotos())) {
            request.setCorporationPhoto(request.getCorporationPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setCorporationPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getDoorPhotos())) {
            request.setDoorPhoto(request.getDoorPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setDoorPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getEvnPhotos())) {
            request.setEvnPhoto(request.getEvnPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setEvnPhoto("");
        }

        if (ObjectUtil.isNotEmpty(request.getDouyinPhotos())) {
            request.setDouyinPhoto(request.getDouyinPhotos().stream().collect(Collectors.joining(",")));
        } else {
            request.setDouyinPhoto("");
        }
        return super.update(retailShopService, request);
    }

    @TraceLog()
    @PostMapping("listPage")
    @ApiOperation("商户信息-查询")
    public Result<List<RetailShopVo>> listPage(@RequestBody ParamReq<RetailShopRequest> req) {
        return super.listPage(retailShopService, req);
    }

    @TraceLog()
    @PostMapping("countPage")
    @ApiOperation("商户信息-统计")
    public Result<Integer> countPage(@RequestBody ParamReq<RetailShopRequest> req) {
        return super.countPage(retailShopService, req);
    }

    @TraceLog()
    @PostMapping("page")
    @ApiOperation("商户信息-分页数据")
    public Result<PageResult> page(@RequestBody ParamReq<RetailShopRequest> req) {
        RetailShopRequest adminRequest = req.getEntity();
        Long adminId = getLoginUserId();
        LoginUser loginUser = LoginUserUtil.getPrincipal();
        if (ObjectUtil.equal(adminRequest.getUserType(), UserTypeEnums.BUSINESS_TYPE.getValue())) {
            if (loginUser.getUserType().equals(UserTypeEnums.SYSTEM_MANAGER_TYPE.getValue())) {
                adminRequest.setSearchOwnerUser(2);
            } else {
                adminRequest.setSearchOwnerUser(1);
                adminRequest.setSearchOwnerUserId(adminId);
            }
        }
        req.setEntity(adminRequest);

        return super.page(retailShopService, req);
    }

    /**
     * 导出数据
     *
     * @param req
     * @return
     */
    @TraceLog()
    @PostMapping("pageExports")
    @ApiOperation("导出导出")
    public void pageExports(@RequestBody ParamReq<RetailShopRequest> req, HttpServletResponse httpServletResponse) throws UnsupportedEncodingException {
        try {
            req.setManagerDept(LoginUserUtil.getPrincipal().getManagerDept());
            req.setCurrent(1);
            Integer count = retailShopService.countPage(req);
            req.setSize(count);
            List<RetailShopVo> list = retailShopService.listPage(req);
            for (RetailShopVo l : list) {
                l.setDredgeDouyin(ObjectUtil.equal("0", l.getDredgeDouyin()) ? "没有" : ObjectUtil.equal("1", l.getDredgeDouyin()) ? "自己上团购" : ObjectUtil.equal("1", l.getDredgeDouyin()) ? "加盟别的品牌" : "");

                l.setDredgeBuy(ObjectUtil.equal("0", l.getDredgeBuy()) ? "未绑定" : ObjectUtil.equal("1", l.getDredgeBuy()) ? "已绑定" : "");
            }
            ExcelWriter writer = ExcelUtil.getWriter();
            writer.writeCellValue(0, 0, "ID");
            writer.writeCellValue(1, 0, "归属城市");
            writer.writeCellValue(2, 0, "归属区域合伙人");
            writer.writeCellValue(3, 0, "商户来源");
            writer.writeCellValue(4, 0, "门店ID");
            writer.writeCellValue(5, 0, "门店名称");
            writer.writeCellValue(6, 0, "营业执照地址");
            writer.writeCellValue(7, 0, "维度");
            writer.writeCellValue(8, 0, "经度");
            writer.writeCellValue(9, 0, "账户ID");
            writer.writeCellValue(10, 0, "账户名称");
            writer.writeCellValue(11, 0, "法人姓名");
            writer.writeCellValue(12, 0, "法人手机号码");
            writer.writeCellValue(13, 0, "门店手机号码");
            writer.writeCellValue(14, 0, "营业执照名称");
            writer.writeCellValue(15, 0, "卫生许可证-1");
            writer.writeCellValue(16, 0, "卫生许可证-2");
            writer.writeCellValue(17, 0, "卫生许可证-3");
            writer.writeCellValue(18, 0, "之前是否开通抖音");
            writer.writeCellValue(19, 0, "之前是否开通团购");
            writer.writeCellValue(20, 0, "营业执照照片-1");
            writer.writeCellValue(21, 0, "营业执照照片-2");
            writer.writeCellValue(22, 0, "营业执照照片-3");
            writer.writeCellValue(23, 0, "法人照片-1");
            writer.writeCellValue(24, 0, "法人照片-2");
            writer.writeCellValue(25, 0, "法人照片-3");
            writer.writeCellValue(26, 0, "法人收款账号");
            writer.writeCellValue(27, 0, "法人开户行");
            writer.writeCellValue(28, 0, "门头照-1");
            writer.writeCellValue(29, 0, "门头照-2");
            writer.writeCellValue(30, 0, "门头照-3");
            writer.writeCellValue(31, 0, "店内环境照-1");
            writer.writeCellValue(32, 0, "店内环境照-2");
            writer.writeCellValue(33, 0, "店内环境照-3");
            writer.writeCellValue(34, 0, "抖音截图-1");
            writer.writeCellValue(35, 0, "抖音截图-2");
            writer.writeCellValue(36, 0, "收货地址");
            writer.writeCellValue(37, 0, "营业时间");

            // 此处表示只写入别名的数据
            // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
            writer.setOnlyAlias(true);

            for (Integer i = 0; i < list.size(); i++) {
                RetailShopVo shopVo = list.get(i);
                writer.writeCellValue(0, i + 1, shopVo.getId());
                writer.writeCellValue(1, i + 1, shopVo.getCity());
                writer.writeCellValue(2, i + 1, shopVo.getOwnerName());
                writer.writeCellValue(3, i + 1, shopVo.getShopSourceName());
                writer.writeCellValue(4, i + 1, shopVo.getPoiId());
                writer.writeCellValue(5, i + 1, shopVo.getPoiName());
                writer.writeCellValue(6, i + 1, shopVo.getAddress());
                writer.writeCellValue(7, i + 1, shopVo.getLatitude());
                writer.writeCellValue(8, i + 1, shopVo.getLongitude());
                writer.writeCellValue(9, i + 1, shopVo.getAccountId());
                writer.writeCellValue(10, i + 1, shopVo.getAccountName());
                writer.writeCellValue(11, i + 1, shopVo.getCorporation());
                writer.writeCellValue(12, i + 1, shopVo.getCorporationPhone());
                writer.writeCellValue(13, i + 1, shopVo.getStorePhone());
                writer.writeCellValue(14, i + 1, shopVo.getBusinessLicense());

                final CountDownLatch latch = new CountDownLatch(17);//使用java并发库concurrent
                AtomicInteger finalI = new AtomicInteger();
                finalI.set(i);
                new Thread(() -> {
                    try {
                        String slps0 = shopVo.getSanitaryLicensePhotos().get(0);
                        if (ObjectUtil.isNotEmpty(slps0)) {
                            writePic(writer, 15, finalI.get() + 1, slps0, Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(15, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(15, finalI.get() + 1, "");
                    }
                    latch.countDown();
                }).start();

                new Thread(() -> {
                    try {
                        String slps1 = shopVo.getSanitaryLicensePhotos().get(1);
                        if (ObjectUtil.isNotEmpty(slps1)) {
                            writePic(writer, 16, finalI.get() + 1, slps1, Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(16, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(16, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();
                new Thread(() -> {
                    try {
                        String slps2 = shopVo.getSanitaryLicensePhotos().get(2);
                        if (ObjectUtil.isNotEmpty(slps2)) {
                            writePic(writer, 17, finalI.get() + 1, slps2, Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(17, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(17, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                writer.writeCellValue(18, i + 1, ObjectUtil.equal(shopVo.getDredgeDouyin(), "0") ? "没有" : ObjectUtil.equal(shopVo.getDredgeDouyin(), "1") ? "自己上的团购" : ObjectUtil.equal(shopVo.getDredgeDouyin(), "2") ? "加盟别的品牌" : "");
                writer.writeCellValue(19, i + 1, ObjectUtil.equal(shopVo.getDredgeBuy(), "0") ? "未绑定" : ObjectUtil.equal(shopVo.getDredgeBuy(), "1") ? "已绑定" : "");

                new Thread(() -> {
                    try {
                        String blps_1 = shopVo.getBusinessLicensePhotos().get(0);
                        if (ObjectUtil.isNotEmpty(blps_1)) {
                            writePic(writer, 20, finalI.get() + 1, blps_1, Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(20, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(20, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                new Thread(() -> {
                    try {
                        String blps_2 = shopVo.getBusinessLicensePhotos().get(1);
                        if (ObjectUtil.isNotEmpty(blps_2)) {
                            writePic(writer, 21, finalI.get() + 1, blps_2, Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(21, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(21, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                new Thread(() -> {
                    try {
                        String blps_3 = shopVo.getBusinessLicensePhotos().get(2);
                        if (ObjectUtil.isNotEmpty(blps_3)) {
                            writePic(writer, 22, finalI.get() + 1, blps_3, Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(22, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(22, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getCorporationPhotos().get(0))) {
                            writePic(writer, 23, finalI.get() + 1, shopVo.getCorporationPhotos().get(0), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(23, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(23, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();
                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getCorporationPhotos()) && ObjectUtil.isNotEmpty(shopVo.getCorporationPhotos().get(1))) {
                            writePic(writer, 24, finalI.get() + 1, shopVo.getCorporationPhotos().get(1), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(24, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(24, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();
                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getCorporationPhotos()) && ObjectUtil.isNotEmpty(shopVo.getCorporationPhotos().get(2))) {
                            writePic(writer, 25, finalI.get() + 1, shopVo.getCorporationPhotos().get(2), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(25, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(25, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                writer.writeCellValue(26, i + 1, shopVo.getCorporationCard());
                writer.writeCellValue(27, i + 1, shopVo.getCorporationCardBank());

                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getDoorPhotos()) && ObjectUtil.isNotEmpty(shopVo.getDoorPhotos().get(0))) {
                            writePic(writer, 28, finalI.get() + 1, shopVo.getDoorPhotos().get(0), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(28, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(28, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getDoorPhotos()) && ObjectUtil.isNotEmpty(shopVo.getDoorPhotos().get(1))) {
                            writePic(writer, 29, finalI.get() + 1, shopVo.getDoorPhotos().get(1), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(29, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(29, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();
                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getDoorPhotos()) && ObjectUtil.isNotEmpty(shopVo.getDoorPhotos().get(2))) {
                            writePic(writer, 30, finalI.get() + 1, shopVo.getDoorPhotos().get(2), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(30, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(30, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getEvnPhotos()) && ObjectUtil.isNotEmpty(shopVo.getEvnPhotos().get(0))) {
                            writePic(writer, 31, finalI.get() + 1, shopVo.getEvnPhotos().get(0), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(31, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(31, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();
                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getEvnPhotos()) && ObjectUtil.isNotEmpty(shopVo.getEvnPhotos().get(1))) {
                            writePic(writer, 32, finalI.get() + 1, shopVo.getEvnPhotos().get(1), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(32, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(32, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();
                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getEvnPhotos()) && ObjectUtil.isNotEmpty(shopVo.getEvnPhotos().get(2))) {
                            writePic(writer, 33, finalI.get() + 1, shopVo.getEvnPhotos().get(2), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(33, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(33, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getDouyinPhotos()) && ObjectUtil.isNotEmpty(shopVo.getDouyinPhotos().get(0))) {
                            writePic(writer, 34, finalI.get() + 1, shopVo.getDouyinPhotos().get(0), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(34, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(34, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();
                new Thread(() -> {
                    try {
                        if (ObjectUtil.isNotEmpty(shopVo.getDouyinPhotos()) && ObjectUtil.isNotEmpty(shopVo.getDouyinPhotos().get(1))) {
                            writePic(writer, 35, finalI.get() + 1, shopVo.getDouyinPhotos().get(1), Workbook.PICTURE_TYPE_JPEG);
                        } else {
                            writer.writeCellValue(35, finalI.get() + 1, "");
                        }
                    } catch (Exception e) {
                        writer.writeCellValue(35, finalI.get() + 1, "");
                    }
                    latch.countDown();//让latch中的数值减一
                }).start();

                latch.await();
                writer.writeCellValue(36, i + 1, shopVo.getDeliveryAddress());
                writer.writeCellValue(37, i + 1, shopVo.getBusinessHour());
            }
//            writer.write(list, true);
            httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
            String excelName = "商户导出记录";
            excelName = URLEncoder.encode(excelName, "utf-8");
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + excelName + ".xls");

            ServletOutputStream excelOut = null;
            excelOut = httpServletResponse.getOutputStream();
            writer.flush(excelOut, true);
            writer.close();
            IoUtil.close(excelOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param writer
     * @param x               单元格x轴坐标
     * @param y               单元格y轴坐标
     * @param pictureDataList 图片列表
     * @param picType         图片格式
     */
    private void writePic(ExcelWriter writer, int x, int y, String pictureDataList, int picType) {
        Sheet sheet = writer.getSheet();
        Drawing drawingPatriarch = sheet.createDrawingPatriarch();

        //设置图片单元格位置
        ClientAnchor anchor = drawingPatriarch.createAnchor(0, 0, 0, 0, x, y, x + 1, y + 1);
        //随单元格改变位置和大小
        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

        //添加图片

        byte[] pictureData = getFileStream(pictureDataList);
        int pictureIndex = sheet.getWorkbook().addPicture(pictureData, picType);
        Picture picture = drawingPatriarch.createPicture(anchor, pictureIndex);
//        picture.resize(); // 调整图片大小

    }

    /**
     * 得到文件流
     *
     * @param url 网络图片URL地址
     * @return
     */
    public static byte[] getFileStream(String url) {
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     *
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 我的商户
     *
     * @param adminId
     * @return
     */
    @GetMapping("adminShopTableTree/{adminId}")
    public Result<List<TableTreeVo>> adminShopTableTree(@PathVariable("adminId") Long adminId) {
        return retailShopClient.adminShopTableTree(adminId);
    }

    @TraceLog()
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除商户信息")
    public Result<Integer> delete(@PathVariable("id") Long id) {
        return super.delete(retailShopService, id);
    }

    @TraceLog()
    @ApiOperation("批量删除商户信息")
    @DeleteMapping("{ids}")
    public Result<Integer> batchDelete(@PathVariable("ids") List<Long> ids) {
        return super.batchDelete(retailShopService, ids);
    }

    @TraceLog()
    @GetMapping("/getShopByOwnerId/{ownerId}")
    public Result<RetailShopVo> getShopByOwnerId(@PathVariable("ownerId") Long ownerId) {
        return retailShopService.getShopByOwnerId(ownerId);
    }

    @TraceLog()
    @PostMapping("updateShopBelong")
    @ApiOperation("更新商户归属")
    public Result<Integer> updateShopBelong(@RequestBody RetailShopRequest request) {
//        request.setCreateUser(LoginUserUtil.getUserId());
        return retailShopService.updateShopBelong(request);
    }

    @TraceLog()
    @PostMapping("updatecityBelong")
    @ApiOperation("更新城市归属")
    public Result<Integer> updatecityBelong(@RequestBody RetailShopRequest request) {
        if (ObjectUtil.isEmpty(request.getIds()) || request.getIds().length == 0) {
            return Result.success("请先选择门店!");
        }

        if (ObjectUtil.isEmpty(request.getCity())) {
            return Result.success("请先选择城市！");
        }

        return retailShopService.updatecityBelong(request);
    }

    @Override
    public Long getLoginUserId() {
        return LoginUserUtil.getUserId();
    }

}
